<template>
  <div class="share-access-container">
    <Header title="文件分享" show-back />

    <div class="share-access-content">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-state">
        <van-loading type="spinner" size="24" />
        <p>正在加载分享信息...</p>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="!shareInfo" class="error-state">
        <van-empty
          image="error"
          description="分享不存在或已过期"
        >
          <van-button type="primary" @click="goHome">
            返回首页
          </van-button>
        </van-empty>
      </div>

      <!-- 分享内容 -->
      <div v-else class="share-content">
        <!-- 分享文件信息 -->
        <div class="file-card">
          <div class="file-icon">
            <van-icon
              :name="getFileIcon(shareInfo.file)"
              :color="getFileIconColor(shareInfo.file)"
              size="40"
            />
          </div>
          <div class="file-info">
            <div class="file-name">{{ shareInfo.shareName }}</div>
            <div class="file-meta">
              <div class="meta-item">
                <span class="label">文件名：</span>
                <span>{{ shareInfo.file.fileName }}</span>
              </div>
              <div v-if="!shareInfo.file.isFolder && shareInfo.file.fileSize" class="meta-item">
                <span class="label">大小：</span>
                <span>{{ formatFileSize(shareInfo.file.fileSize) }}</span>
              </div>
              <div class="meta-item">
                <span class="label">分享时间：</span>
                <span>{{ formatDateTime(shareInfo.file.createTime) }}</span>
              </div>
              <div class="meta-item">
                <span class="label">有效期：</span>
                <span>{{ shareInfo.expireTime ? formatDateTime(shareInfo.expireTime) : '永久有效' }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 密码验证 -->
        <div v-if="shareInfo.needPassword && !isVerified" class="password-section">
          <van-cell-group title="请输入提取码" inset>
            <van-field
              v-model="password"
              label="提取码"
              placeholder="请输入4位提取码"
              maxlength="4"
              :error-message="passwordError"
              @keyup.enter="handleVerifyPassword"
            />
          </van-cell-group>

          <div class="password-actions">
            <van-button
              block
              type="primary"
              :loading="verifying"
              @click="handleVerifyPassword"
            >
              验证提取码
            </van-button>
          </div>
        </div>

        <!-- 文件操作 -->
        <div v-if="!shareInfo.needPassword || isVerified" class="file-actions">
          <van-cell-group title="文件操作" inset>
            <van-cell
              title="预览文件"
              is-link
              @click="handlePreview"
              v-if="canPreview"
            >
              <template #icon>
                <van-icon name="eye-o" />
              </template>
            </van-cell>

            <van-cell
              title="下载文件"
              is-link
              @click="handleDownload"
              v-if="canDownload"
            >
              <template #icon>
                <van-icon name="down" />
              </template>
            </van-cell>
          </van-cell-group>

          <!-- 分享统计 -->
          <div class="share-stats">
            <div class="stat-item">
              <span class="stat-label">访问次数</span>
              <span class="stat-value">{{ shareInfo.visitCount }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">下载次数</span>
              <span class="stat-value">{{ shareInfo.downloadCount }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showLoadingToast, closeToast } from 'vant'
import Header from '@/components/Header.vue'
import {
  getShare,
  verifySharePassword,
  recordShareDownload,
  type ShareAccessResponse,
  type ShareVerifyResponse
} from '@/api/share'
import { generateDownloadUrl } from '@/api/file'
import type { FileInfo } from '@/api/file'

const router = useRouter()
const route = useRoute()

// 状态
const loading = ref(true)
const verifying = ref(false)
const shareInfo = ref<ShareAccessResponse | null>(null)
const isVerified = ref(false)
const password = ref('')
const passwordError = ref('')

// 计算属性
const canPreview = computed(() => {
  if (!shareInfo.value) return false

  // 根据权限判断
  const permissions = shareInfo.value.permissions
  return permissions >= 1 // 1-仅预览, 2-可下载
})

const canDownload = computed(() => {
  if (!shareInfo.value) return false

  // 根据权限判断
  const permissions = shareInfo.value.permissions
  return permissions >= 2 // 2-可下载
})

// 方法
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'

  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))

  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatDateTime = (dateStr: string): string => {
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getFileIcon = (file: FileInfo) => {
  if (file.isFolder === 1) {
    return 'folder-o'
  }

  const ext = file.fileName.split('.').pop()?.toLowerCase()
  switch (ext) {
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
    case 'bmp':
    case 'webp':
      return 'photo-o'
    case 'mp4':
    case 'avi':
    case 'mov':
    case 'wmv':
    case 'flv':
      return 'video-o'
    case 'mp3':
    case 'wav':
    case 'aac':
    case 'flac':
      return 'music-o'
    case 'pdf':
      return 'description'
    case 'doc':
    case 'docx':
      return 'description'
    case 'xls':
    case 'xlsx':
      return 'description'
    case 'ppt':
    case 'pptx':
      return 'description'
    case 'txt':
      return 'notes-o'
    case 'zip':
    case 'rar':
    case '7z':
      return 'bag-o'
    default:
      return 'description'
  }
}

const getFileIconColor = (file: FileInfo) => {
  if (file.isFolder === 1) {
    return '#1989fa'
  }

  const ext = file.fileName.split('.').pop()?.toLowerCase()
  switch (ext) {
    case 'jpg':
    case 'jpeg':
    case 'png':
    case 'gif':
    case 'bmp':
    case 'webp':
      return '#ff976a'
    case 'mp4':
    case 'avi':
    case 'mov':
    case 'wmv':
    case 'flv':
      return '#ff976a'
    case 'mp3':
    case 'wav':
    case 'aac':
    case 'flac':
      return '#07c160'
    case 'pdf':
      return '#ee0a24'
    case 'doc':
    case 'docx':
      return '#1989fa'
    case 'xls':
    case 'xlsx':
      return '#07c160'
    case 'ppt':
    case 'pptx':
      return '#ff976a'
    default:
      return '#969799'
  }
}

const goHome = () => {
  router.push('/')
}

const loadShareInfo = async () => {
  const shareCode = route.params.shareCode as string

  if (!shareCode) {
    showToast('分享码不能为空')
    router.push('/')
    return
  }

  try {
    loading.value = true
    const response = await getShare(shareCode)
    shareInfo.value = response

    // 如果不需要密码，直接标记为已验证
    if (!response.needPassword) {
      isVerified.value = true
    }
  } catch (error: any) {
    console.error('获取分享信息失败:', error)
    showToast({
      type: 'fail',
      message: error.message || '获取分享信息失败'
    })
    shareInfo.value = null
  } finally {
    loading.value = false
  }
}

const handleVerifyPassword = async () => {
  if (!password.value) {
    passwordError.value = '请输入提取码'
    return
  }

  if (password.value.length !== 4) {
    passwordError.value = '提取码必须是4位'
    return
  }

  const shareCode = route.params.shareCode as string

  try {
    verifying.value = true
    passwordError.value = ''

    const response = await verifySharePassword(shareCode, password.value)

    if (response.verified) {
      isVerified.value = true
      showToast({
        type: 'success',
        message: '验证成功'
      })
    } else {
      passwordError.value = '提取码错误'
    }
  } catch (error: any) {
    passwordError.value = error.message || '验证失败'
  } finally {
    verifying.value = false
  }
}

const handlePreview = () => {
  if (!shareInfo.value || !canPreview.value) return

  // 跳转到预览页面
  router.push(`/preview/${shareInfo.value.file.id}`)
}

const handleDownload = async () => {
  if (!shareInfo.value || !canDownload.value) return

  try {
    showLoadingToast({
      message: '正在生成下载链接...',
      duration: 0
    })

    // 生成下载链接
    const downloadInfo = await generateDownloadUrl(shareInfo.value.file.id)

    // 记录下载统计
    const shareCode = route.params.shareCode as string
    await recordShareDownload(shareCode)

    closeToast()

    // 创建下载链接
    const link = document.createElement('a')
    link.href = downloadInfo.downloadUrl
    link.download = shareInfo.value.file.fileName
    link.target = '_blank'

    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    // 更新下载次数显示
    if (shareInfo.value) {
      shareInfo.value.downloadCount++
    }

    showToast({
      type: 'success',
      message: '开始下载'
    })
  } catch (error: any) {
    closeToast()
    showToast({
      type: 'fail',
      message: error.message || '下载失败'
    })
  }
}

onMounted(() => {
  loadShareInfo()
})
</script>

<style scoped>
.share-access-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f8f8f8;
}

.share-access-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #969799;
}

.loading-state p {
  margin-top: 12px;
  font-size: 14px;
}

.error-state {
  padding: 40px 20px;
}

.file-card {
  display: flex;
  align-items: flex-start;
  padding: 20px;
  margin-bottom: 16px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.file-icon {
  margin-right: 16px;
  flex-shrink: 0;
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: 18px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 12px;
  word-break: break-all;
}

.file-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.meta-item {
  display: flex;
  font-size: 14px;
  line-height: 1.4;
}

.label {
  color: #969799;
  margin-right: 8px;
  flex-shrink: 0;
}

.password-section {
  margin-bottom: 16px;
}

.password-actions {
  padding: 16px;
}

.file-actions {
  margin-bottom: 16px;
}

.share-stats {
  display: flex;
  justify-content: space-around;
  padding: 16px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.stat-label {
  font-size: 12px;
  color: #969799;
}

.stat-value {
  font-size: 18px;
  font-weight: 600;
  color: #323233;
}

:deep(.van-cell-group--inset) {
  margin: 16px 0;
}

:deep(.van-empty) {
  padding: 60px 20px;
}
</style>